<template>
<div class="search-suggestion">
<van-cell-group>
  <van-cell value="搜索建议">
   <template #right-icon>
    <van-icon name="delete-o" />
  </template>
</van-cell>
 <van-cell v-for="(text,index) in list" :key="index" @click="$emit('search',text)">
   <div slot="title" v-html="highlightText(text)"></div>
 </van-cell>
</van-cell-group>
</div>
</template>
<script>
import { search } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    searchText: {
      handler: debounce(function (val) {
        this.loadSearchSuggestion(val)
      }, 1000),
      immediate: true
    }
  },
  data () {
    return {
      list: []
    }
  },
  created () {

  },
  methods: {
    async loadSearchSuggestion (q) {
      try {
        const res = await search(q)
        console.log(res)
        this.list = res.data.data.options
      } catch (err) {
        this.$toast('获取失败')
      }
    },
    highlightText (text) {
      const highlightStr = `<span class="active">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highlightStr)
    }
  }
}
</script>

<style scoped lang="less">
.search-suggestion {
   /deep/ span.active {
  color: blue;
}
}
</style>
